import React from 'react';
import './notify.scss';

let EventList = [];
let CloseEventList = [];

class ReactNotificationComponent extends React.Component {
    constructor(props, context) {
        super(props, context);

        this.state = {};
    }

    async onNotifyEvent(msg, options = {}) {
        //options 待定
        this._?.();
        clearTimeout(this.time);
        this.setState({
            visibility: true,
            message: msg,
            ...options
        });

        return new Promise(_ => {
            this._ = _;
            this.time = setTimeout(() => {
                _(true);
                this.setState({
                    visibility: false
                });
            }, options.duration || 2000);
        });
    }

    async onCloseEvent() {
        this._?.();
        clearTimeout(this.time);
        this.setState({
            visibility: false
        });

        return true;
    }

    componentDidMount() {
        EventList.push((...args) => this.onNotifyEvent(...args));
        CloseEventList.push(() => this.onCloseEvent());
    }

    render() {
        return (
            <div
                className={"--notify-container" + (this.state.shelter ? ' shelter' : '') + (this.state.visibility ? ' on' : '')}>
                <div className="--show">
                    <div>{this.state.message}</div>
                </div>
            </div>
        );
    }
}

export default ReactNotificationComponent;

export function notify(msg, options) {
    if (EventList.length > 0) {
        return EventList[0](msg, options);
    }

    return Promise.resolve(false);
}

export function clear() {
    if (CloseEventList.length > 0) {
        return CloseEventList[0]();
    }

    return Promise.resolve(false);
}